package it.trekker.dao.ejb;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import it.trekker.dao.Excursion;
import it.trekker.dao.Photo;
import it.trekker.dao.IPhotoDAO;

@Stateless
@Local(IPhotoDAO.class)
public class EJB3PhotoDAO implements IPhotoDAO {
	
	@PersistenceContext(unitName = "TrekkerUnit")
	protected EntityManager em;

	public int insert(Photo photo) {
		if(photo != null) {
			em.persist(photo);
			return photo.getId();
		}
		
		return 0;
	}

	public int remove(int id) {
		Photo photo = findPhotoById(id);
		
		if(photo != null) {
			em.remove(photo);
			return id;
		}
		
		return 0;
	}

	public int update(Photo photo) {
		if(photo != null) {
			if(em.merge(photo) != null)
				return photo.getId();
		}
		return 0;
	}

	public Photo findPhotoById(int id) {
		return em.find(Photo.class, id);
	}

	public List<Photo> findPhotosByExcursion(Excursion excursion) {
		if(excursion != null) {
			excursion = em.merge(excursion);
			
			return em.createQuery(
					"SELECT DISTINCT (p) FROM Photo p JOIN FETCH p.excursion " +
							"WHERE p.excursion = :excursion"
					).setParameter("excursion", excursion).getResultList();
		}
		
		return null;
	}

	public List<Photo> findAllPhotos() {
		return em.createQuery("from Photo").getResultList();
	}

}
